import { memo, useState } from 'react';

const MemoParent = () => {
    const [count, setCount] = useState(0);
    const [profile, setProfile] = useState({ name: 'leslie', age: 19 });

    const handleClick = () => {
        setCount(count + 1);
    };

    const handleName = () => {
        setProfile({ ...profile, name: 'leslie su' });
    };

    const handleAge = () => {
        setProfile({ ...profile, age: 20 });
    };

    return (
        <div>
            <h1>MemoParent {count}</h1>
            <div style={{ display: "flex", gap: "1rem" }}>
                <button className="px-4 py-2 m-1 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors" onClick={handleClick}>点击更新count</button>
                <button className="px-4 py-2 m-1 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors" onClick={handleName}>点击更新name</button>
                <button className="px-4 py-2 m-1 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors" onClick={handleAge}>点击更新age</button>
            </div>

            <WithoutMemo age={profile.age} name={profile.name} />
            <WithMemo age={profile.age} name={profile.name} />
        </div>
    );
};

export default MemoParent;


const WithoutMemo = ({ name, age }: { name: string, age: number }) => {
    console.log('WithoutMemo渲染');
    return (
        <div>
            <h1>WithoutMemo</h1>
            <p>name: {name}</p>
            <p>age: {age}</p>
        </div>
    );
};

const WithMemo = memo(({ name, age }: { name: string, age: number }) => {
    console.log('WithMemo渲染');
    return (
        <div>
            <h1>WithMemo</h1>
            <p>name: {name}</p>
            <p>age: {age}</p>
        </div>
    );
});